package middleware

import (
	"context"
	"fmt"
	"github.com/go-chi/render"
	"net/http"
	appRender "gsc-datasets/internal/rest/render"
	"gsc-datasets/internal/rest/routers"
	"gsc-datasets/pkg/util"
)

func WithUser(rr *routers.RestRouter, userKey util.ContextKey) func(http.Handler) http.Handler {
	logger := rr.Logger("WithUser")
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			mockID := r.Header.Get(util.MockIDKey)
			if util.IsEmpty(mockID) {
				render.Render(w, r, appRender.ErrBadRequest(fmt.Errorf("mock-id")))
				return
			}
			logger.Infof("mock_id=>%s", mockID)
			ctx := r.Context()
			user, err := rr.Dao().GetUserByMockID(ctx, mockID)
			if err != nil {
				render.Render(w, r, appRender.ErrRender(err))
				return
			}
			ctx = context.WithValue(ctx, userKey,  &user)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}
